const mongoose = require("mongoose");
// const { md5 } = require("tools-factory-tang/salt");
// 引用token加密包
// const { createToken } = require("tools-factory-tang/jwt");

// 等待注册账号值的接收
const adminsReg = async ({ adminsname, adminspassword }) => {
    // 使用工具包方法加密密码，明文加密成密文
    // adminspassword = md5(adminspassword);
    // 获取model对象
    const adminsModel = mongoose.model("admins");
    // 查找注册账号是否存在
    const data = await adminsModel.findOne({ adminsname, adminspassword });
    if (data) {
        // 给登录数据库添加用户名
        return { status: false };
    } else {
        await adminsModel.create({ adminsname, adminspassword });
        return { status: true };

    }
};
// 登录
const adminsLogin = async ({ adminsname, adminspassword }) => {
    // console.log(adminsname, adminspassword);
    // 使用工具包方法加密密码，明文加密成密文
    // adminspassword = md5(adminspassword);
    // 获取model对象
    const adminsModel = mongoose.model("admins");
    // 查找数据库，判断账号密码是否输入正确 findOne即查找到一个匹配数据立即返回
    return await adminsModel.findOne({adminsname,adminspassword});
};


// 暴露接口
module.exports={adminsLogin,adminsReg}
const { adminsModel } = require("../db/model/admins.js")

const get = async ({ curPage, eachPage }) => {
    (curPage = ~~curPage), (eachPage = ~~eachPage);
    const data = {
        total: 0,
        maxPage: 0,
        rows: [],
    };
    //获取当前model映射的集合中的文档总数
    data.total = await adminsModel.countDocuments();
    //获取总页数
    data.maxPage = Math.ceil(data.total / eachPage);
    const skipNum = (curPage - 1) * eachPage;
    // 获取页面渲染数据

    data.rows = await adminsModel.find().skip(skipNum).limit(eachPage).sort({ _id: -1 }).exec();

    return data

};

// query(查询条件),params(修改的属性)
const updata = async (query, params) => {
    const adminsModel = mongoose.model("admins");
    return await adminsModel.updateOne(query, params)
}
// 通过id获取数据
const getOne = async _id => {
    const adminsModel = mongoose.model("admins");
    return await adminsModel.findOne({ _id })
}

// 新增电影接口
const add = async ({_id,username,password}) => {
    const adminsModel = mongoose.model("admins");
    return await adminsModel.create({_id,username,password})
}

const findOne = async _id => {
    // model传一个参数时表示获取这个model对象
    const adminsModel = mongoose.model("admins");
    // 添加学生数据
    return await adminsModel.findOne({ _id });
}

// 修改
const changeadmins = async (newData) => {
    const adminsModel = mongoose.model("admins");
    await adminsModel.update({ _id: newData._id }, newData);
}




// 删除电影信息
const remove = async ({ _id }) => {
    const adminsModel = mongoose.model("admins");
    // console.log({_id});
    //   console.log("添加时",{name,age,gender,address,phone,zip,gradle,email},"end");
    await adminsModel.remove({ _id });
}

module.exports = { get, add, getOne, updata, remove, findOne,  changeadmins,adminsLogin,adminsReg };
